<?php

namespace app\admin\controller;

use app\admin\service\AdminService;
use support\spark\exception\ApiException;
use support\spark\model\system\AdminRole;
use support\spark\model\system\AdminUser;
use support\Request;

class AdminController extends Curd
{

    public function index()
    {
        if (request()->isAjax()) {
            $adminService = new AdminService();
            $res = $adminService->getList(request()->all());
            return sparkSuccess($res);
        }
        return view('admin/index');
    }

    /**
     * 添加管理员
     */
    public function add()
    {
        if (request()->isAjaxPost()) {
            $param = request()->post();
            $adminService = new AdminService();
            $res = $adminService->addAdmin($param);
            return sparkSuccess($res);
        }
        $adminRoleModel = new AdminRole();
        $where[] = ['status', '=', 1];
        $where[] = ['id', '>', 1];
        return sparkSuccess(dataReturn(0, 'ok', $adminRoleModel->getAllList($where)));
    }

    /**
     * 编辑管理员
     */
    public function edit()
    {
        if (request()->isAjaxPost()) {
            $param = request()->post();
            $adminService = new AdminService();
            $res = $adminService->editAdmin($param);
            return sparkSuccess($res);
        }
        $adminRoleModel = new AdminRole();
        $where[] = ['status', '=', 1];
        $where[] = ['id', '>', 1];
        return sparkSuccess(dataReturn(0, 'ok', $adminRoleModel->getAllList($where)));
    }

    /**
     * 删除管理员
     */
    public function del(Request $request)
    {
        $id = $request->input('id');
        if ($id === 1) {
            throw new ApiException('超级管理员不可以删除', -1);
        }
        $adminUserModel = new AdminUser();
        $adminUserModel->delById($id);
        return sparkSuccess(dataReturn(0, '删除成功'));
    }
}